package com.koocloud.electroplatemanage.service.impl;

import cn.hutool.core.lang.Validator;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.koocloud.electroplatemanage.auth.mapper.IUserDao;
import com.koocloud.electroplatemanage.common.pojo.ResponseTemplate;
import com.koocloud.electroplatemanage.mapper.*;
import com.koocloud.electroplatemanage.pojo.*;
import com.koocloud.electroplatemanage.pojo.Process;
import com.koocloud.electroplatemanage.pojo.mainpojo.OrderResource;
import com.koocloud.electroplatemanage.pojo.mainpojo.WIP;
import com.koocloud.electroplatemanage.service.WorkProcessService;
import com.koocloud.electroplatemanage.utils.HexUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

import static com.koocloud.electroplatemanage.constant.MainWIPRouteConstant.*;

/**
 * @program: Information_platform
 * @description: 主要工道及其过程记录实现层
 * @author: xxc
 * @create: 2020-11-16 14:37
 */
@Service
@Transactional(rollbackFor=Exception.class)
public class WorkProcessServiceImpl implements WorkProcessService {
    @Resource
    private IUserDao iUserDao;
    @Resource
    private ProcessMapper processMapper;
    @Resource
    private WorkProcessMapper workProcessMapper;
    @Resource
    private ProcessParameterMapper processParameterMapper;
    @Resource
    private MainProductionMapper mainProductionMapper;
    @Resource
    private ProductionTaskMapper productionTaskMapper;
    @Resource
    private ProductCompletedMapper productCompletedMapper;
    Lock lock = new ReentrantLock();

    /**
     *@Description: 根据工单号查询数据
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectByWorkOrderNumber(String workOrderNumber) {
        try {
            WorkProcessVo workProcessVo = workProcessMapper.selectByWorkOrderNumber(workOrderNumber);
            if (!StringUtils.isEmpty(workProcessVo)){
                List<ProcessParameter> processParameterList = workProcessMapper.selectByWorkOrderNumberResult(workOrderNumber);
                workProcessVo.setProcessParameterList(processParameterList);
            }
            //判断查表操作是否成功
            if (null != workProcessVo) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(workProcessVo).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description: 添加时使用的模板
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectByWorkOrderNumberTemplate(String workOrderNumber) {
        try {
/*            //查询当前工单号所使用的表面处理过程
            Process process = processMapper.selectByWorkOrderNumber(workOrderNumber);
            //查询当前表面处理过程的工序
            ProcessParameter processParameter = processParameterMapper.selectByProcessSpecification(process.getProcessSpecification());
            //创建主要工道及其过程实体
            WorkProcessVo workProcessVo = new WorkProcessVo();
            workProcessVo.setWorkOrderNumber(process.getWorkOrderNumber());
            workProcessVo.setProcessSpecification(process.getProcessSpecification());
            //主要工道及其过程的工序
            workProcessVo.setProcessParameterList(processParameterMapper.selectByFatherId(processParameter.getId()));*/
            //判断查表操作是否成功
            WorkProcessVo workProcessVo = workProcessMapper.selectByWorkOrderNumber(workOrderNumber);
            if (!StringUtils.isEmpty(workProcessVo)){
                List<ProcessParameter> processParameterList = workProcessMapper.selectByWorkOrderNumberResult(workOrderNumber);
                workProcessVo.setProcessParameterList(processParameterList);
            }
            if (null != workProcessVo) {
                //查表成功返回数据
                return ResponseTemplate.builder().code(0).message("查询成功").count(1l).data(workProcessVo).build();
            } else {
                //查表失败返回提示
                return ResponseTemplate.builder().code(1).message("没有此数据").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }
    }

    /**
     *@Description: 对主要工道及其过程记录进行全表查询
     *@Param: [page, limit, workProcessVo]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate selectAllData(String page, String limit, WorkProcessVo workProcessVo) {
        //校验分页参数是否为纯数字 并且page和limit不都等于0
        if(Validator.isNumber(page)&&Validator.isNumber(limit)&&!("0".equals(page)&&"0".equals(limit))) {
            try {
                lock.lock();
                int rows = -1;
                //开始查询在工表，状态为5的插入生产
                List<WIP> wipList= mainProductionMapper.selectAllWIPByLocation(PRODUCTION);
                if(!StringUtils.isEmpty(wipList)) {
                    for(WIP wip:wipList) {
                        //获取工单号
                        if(!StringUtils.isEmpty(wip.getWorkOrderNumber())) {
                            //数据库重复工单号校验
                            int count = workProcessMapper.selectWorkOrderNumberCount(wip.getWorkOrderNumber());
                            if(count>0) {
                                continue;
                            }
                            //判断是否为拆分的工单号
                            ProductionTask productionTask = productionTaskMapper.selectByWorkOrderNumber(wip.getWorkOrderNumber());
                            if(StringUtils.isEmpty(productionTask)) {
                                continue;
                            }
                            String workOrderNumber = null;
                            if(productionTask.getWorkOrderNumber().equals(productionTask.getPlanWorkOrderNumber())){
                                //未拆分
                                workOrderNumber = wip.getWorkOrderNumber();
                            }else {
                                //拆分
                                workOrderNumber = productionTask.getPlanWorkOrderNumber();
                            }
                            //创建主要工序实体
                            WorkProcessVo insertWorkProcessVo = new WorkProcessVo();
                            //设置工单号
                            insertWorkProcessVo.setWorkOrderNumber(wip.getWorkOrderNumber());
                            //查询当前工单号所使用的表面处理过程
                            Process process = processMapper.selectByWorkOrderNumber(workOrderNumber);
                            if(!StringUtils.isEmpty(process.getProcessSpecification())) {
                                //设置工艺规程
                                insertWorkProcessVo.setProcessSpecification(process.getProcessSpecification());
                            }
                            //设置删除标志
                            insertWorkProcessVo.setDeleteFlag("1");
                            if(!StringUtils.isEmpty(wip.getEntryTime())) {
                                //设置创建时间
                                insertWorkProcessVo.setCreateTime(wip.getEntryTime());
                            }
                            if(!StringUtils.isEmpty(wip.getEntryPerson())) {
                                //设置创建人
                                insertWorkProcessVo.setCreator(wip.getEntryPerson());
                            }

                            //查询当前表面处理过程的工序
                            ProcessParameter processParameter = processParameterMapper.selectByProcessSpecification(process.getProcessSpecification());
                            //主要工道及其过程的工序
                            for (ProcessParameter parameter:processParameterMapper.selectByFatherId(processParameter.getId())) {
                                parameter.setWorkOrderNumber(insertWorkProcessVo.getWorkOrderNumber());
                                workProcessMapper.insertWorkProcessResult(parameter);
                            }
                            //记录成功插入条数
                            rows = workProcessMapper.insert(insertWorkProcessVo);
                        }
                    }
                }
                //在工表插入完成后开始查询
                if(StringUtils.isEmpty(wipList)||(wipList.size()>0&&rows>0)||(wipList.size()>=0&&rows==-1)) {
                    //开始分页
                    PageHelper.startPage(Integer.valueOf(page), Integer.valueOf(limit));
                    //全局查询
                    List<WorkProcessVo> WorkProcessList = workProcessMapper.selectAllData(workProcessVo);
                    //构造分页实体
                    PageInfo<WorkProcessVo> info=new PageInfo<>(WorkProcessList);
                    if (info.getTotal()>0) {
                        //查询到数据
                        return ResponseTemplate.builder().code(0).message("查询成功").count(info.getTotal()).data(info.getList()).build();
                    } else {
                        //没有查询到数据
                        return ResponseTemplate.builder().code(1).message("没有查到对应数据").count(0l).build();
                    }
                }
                else {
                    return ResponseTemplate.builder().code(1).message("主要工序表数据导入失败").count(0l).build();
                }
            } catch (Exception e) {
                //遇到异常，返回异常原因
                e.printStackTrace();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
            }finally {
                lock.unlock();
            }
        } else {
            return ResponseTemplate.builder().code(1).message("分页参数错误").count(0l).build();
        }
    }

    /**
     *@Description:  新增一条数据
     *@Param: [workProcessVo, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate insert(WorkProcessVo workProcessVo, String userId) {
        try{
            lock.lock();
            //获取创建人
            User user = iUserDao.selectByPk(userId);
            //设置创建人
            workProcessVo.setCreator(user.getJobNum());
            //插入一条记录
            int row = workProcessMapper.insert(workProcessVo);
            int sum = 0;
            for (ProcessParameter processParameter:workProcessVo.getProcessParameterList()) {
                processParameter.setWorkOrderNumber(workProcessVo.getWorkOrderNumber());
                int rows = processParameterMapper.insert(processParameter);
                if (rows >0){
                    sum ++;
                }
            }
            if (row > 0 && sum > 0) {
                return ResponseTemplate.builder().code(0).message("插入数据成功").count(1l).build();
            } else {//没有异常并且插入数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("插入数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 逻辑删除一条数据
     *@Param: [id, userId, deleteFlag]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate delete(String id, String userId, String deleteFlag) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
            //逻辑删除一条记录
            int rows = workProcessMapper.delete(id,user.getJobNum(),deleteFlag);
            //判断删除操作是否成功
            if (rows > 0) {
                //删除成功返回数据
                return ResponseTemplate.builder().code(0).message("删除成功").count(1l).build();
            } else {
                //删除失败返回提示
                return ResponseTemplate.builder().code(1).message("删除失败").count(0l).build();
            }
        } catch (Exception e) {
            //遇到异常，返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }

    }

    /**
     *@Description: 修改一条数据
     *@Param: [workProcessVo, userId]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/16
     */
    @Override
    public ResponseTemplate update(WorkProcessVo workProcessVo, String userId) {
        try {
            lock.lock();
            //获取修改人
            User user = iUserDao.selectByPk(userId);
        /*    //测试数据 需要前端传参
            workProcessVo.setWorkOrderNumber("202011120013");*/
            workProcessVo.setDeleteFlag("1");
            //设置修改人
            workProcessVo.setModifier(user.getJobNum());
            //没有异常并且修改数据条数大于0
            int row = workProcessMapper.update(workProcessVo);
            int sum = 0;
            //查询表体记录数，用作新增或者编辑操作判断
            int count = workProcessMapper.selectResultWorkNumberCount(workProcessVo.getWorkOrderNumber());
            //编辑操作
            if(count==workProcessVo.getProcessParameterList().size()) {
                for (ProcessParameter processParameter:workProcessVo.getProcessParameterList()) {
                    processParameter.setWorkOrderNumber(workProcessVo.getWorkOrderNumber());
                    int rows = processParameterMapper.update(processParameter);
                    if (rows >0){
                        sum ++;
                    }
                }
            }
            //新增操作
            else {
                for (ProcessParameter processParameter:workProcessVo.getProcessParameterList()) {
                    processParameter.setWorkOrderNumber(workProcessVo.getWorkOrderNumber());
                    int rows = processParameterMapper.insert(processParameter);
                    if (rows >0){
                        sum ++;
                    }
                }
            }
            if(row > 0 && sum > 0) {
                return ResponseTemplate.builder().code(0).message("修改数据成功").count(1l).build();
            }
            else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("修改数据失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 生产结束确认按钮
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: xxc
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate confirmEntryInfo(String workOrderNumber, String userId) {
        try{
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(userId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变主要工序状态
            workProcessMapper.changeState(workOrderNumber);
            /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(PROCESSPREPARATION);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
            //生产在工表
            WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
            wip.setCurrentLocation(WORKCOMPLETED);
            int rows =  mainProductionMapper.updateWIP(wip);
            //生产实际表
            String postion = PRODUCTION;
            List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
            OrderResource orderResource = orderResourceList.get(0);
            //上一状态完成时间
            orderResource.setCompletionTime(strDate);
            //上一状态完成人
            orderResource.setCompletedPerson(user.getJobNum());
            mainProductionMapper.updateOrderResource(orderResource);
            orderResource.setRoutePosition(WORKCOMPLETED);
            //投入时间
            orderResource.setEntryTime(strDate);
            //投入人
            orderResource.setEntryPerson(user.getJobNum());
            //上一状态完成时间
            orderResource.setCompletionTime(null);
            //上一状态完成人
            orderResource.setCompletedPerson(null);
            int  row = mainProductionMapper.insertOrderResource(orderResource);
            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("确认失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }

    /**
     *@Description: 生产完成确认按钮
     *@Param: [workOrderNumber]
     *@return: com.koocloud.electroplatemanage.common.pojo.ResponseTemplate
     *@Author: wjx
     *@date: 2020/11/19
     */
    @Override
    public ResponseTemplate confirmCompletedInfo(String workOrderNumber, String userId) {
        try{
            lock.lock();
            //操作人
            User user = iUserDao.selectByPk(userId);
            Date date = new Date();//获取当前的日期
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            String strDate = df.format(date);//获取String类型的时间
            //改变任务单状态
            workProcessMapper.changeState2(workOrderNumber);
            //改变生产完工表状态
            productCompletedMapper.changeState(workOrderNumber);
            /*//工单号表
            WorkOrder workOrder = mainProductionMapper.selectWorkOrderByPk(workOrderNumber);
            workOrder.setCurrentLocation(PROCESSPREPARATION);
            int limit = mainProductionMapper.updateWorkOrder(workOrder);*/
            //生产在工表
            WIP wip = mainProductionMapper.selectWIPByPk(workOrderNumber);
            wip.setCurrentLocation(CHECK);
            int rows =  mainProductionMapper.updateWIP(wip);
            //生产实际表
            String postion = WORKCOMPLETED;
            List<OrderResource> orderResourceList = mainProductionMapper.selectOrderResourceByworkOrderNumber(workOrderNumber,postion);
            //orderResource.setRoutePosition(CHECK);
            int row = 0;
            if(!StringUtils.isEmpty(orderResourceList.get(0))) {
                OrderResource orderResource = orderResourceList.get(0);
                //上一状态完成时间
                orderResource.setCompletionTime(strDate);
                //上一状态完成人
                orderResource.setCompletedPerson(user.getJobNum());
                mainProductionMapper.updateOrderResource(orderResource);
                orderResource.setRoutePosition(CHECK);
                //投入时间
                orderResource.setEntryTime(strDate);
                //投入人
                orderResource.setEntryPerson(user.getJobNum());
                //上一状态完成时间
                orderResource.setCompletionTime(null);
                //上一状态完成人
                orderResource.setCompletedPerson(null);
                row = mainProductionMapper.insertOrderResource(orderResource);

            }
            //int  row = mainProductionMapper.insertOrderResource(orderResource);
            if(rows>0 && row >0) {
                return ResponseTemplate.builder().code(0).message("确认成功").count(1l).build();
            } else {//没有异常并且修改数据失败，原则上不出现
                return ResponseTemplate.builder().code(1).message("确认失败").count(0l).build();
            }
        } catch (Exception e) {
            //出现异常返回异常原因
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseTemplate.builder().code(1).message(e.getMessage()).count(0l).build();
        }finally {
            lock.unlock();
        }
    }
}
